package com.bestcem.xm.om.service.impl;

import com.bestcem.bp.xm.user.grpc.v1.services.Organization;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.om.dao.OmIndustryDao;
import com.bestcem.xm.om.dao.OmUserPackDao;
import com.bestcem.xm.om.dao.UserModulePackDao;
import com.bestcem.xm.om.dao.mapper.UserDomainMapper;
import com.bestcem.xm.om.dao.mapper.UserMmoduleMapper;
import com.bestcem.xm.om.dao.mapper.UserSubmoduleMapper;
import com.bestcem.xm.om.entity.*;
import com.bestcem.xm.om.enums.OpenPlantFormBookingIndustryEnum;
import com.bestcem.xm.om.enums.PackEditionEnum;
import com.bestcem.xm.om.enums.PackageCategoryEnum;
import com.bestcem.xm.om.enums.PackageTypeEnum;
import com.bestcem.xm.om.enums.pack.MModuleCategoryEnum;
import com.bestcem.xm.om.grpc.client.OmOrgGrpcService;
import com.bestcem.xm.om.service.InitDataService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.om.constant.RedisKeyConstant.USER_PACK_PERM;

/**
 * 数据初始化实现类
 *
 * @author YiFang <yifang.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/1 10:32
 */
@Slf4j
@Service
public class InitDataServiceImpl implements InitDataService {
    private static final String STRUCT_KEY = "app:om:pack:struct";
    @Resource
    OmIndustryDao omIndustryDao;
    @Resource
    OmUserPackDao omUserPackDao;
    @Resource
    UserModulePackDao userModulePackDao;
    @Resource
    UserMmoduleMapper userMmoduleMapper;
    @Resource
    private UserDomainMapper userDomainMapper;
    @Resource
    private UserSubmoduleMapper userSubmoduleMapper;
    @Resource
    private OmOrgGrpcService omOrgGrpcService;
    @Resource
    private RedisService redisUtil;
    @Value("${app.xm.is-baseline:true}")
    private boolean isBaseline;
    @Value("${app.om.single.org-info.code: ''}")
    private String singleOrgCode;

    @Override
    public ServiceResult<Void> initData() {
        initModule();
        initSubmodule();
        initDomain();
        initIndustry();

        if (isBaseline) {
            initFlagShipPack("旗舰版");
            deletePackageCache();
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<String> mergePackage() {
        // 账号管理子模块code
        String accountCode = "ACCOUNT";
        UserSubmodule accountSubmodule = new UserSubmodule();
        accountSubmodule.setCode(accountCode);
        List<UserSubmodule> userSubmodules = userSubmoduleMapper.queryAllByLimit(accountSubmodule);
        if (!CollectionUtils.isEmpty(userSubmodules)) {
            // 账号管理子模块id
            String submoduleId = userSubmodules.get(0).getId();

            // 层级组织(编辑/上传/下载) 功能code
            String groupCode = "GROUP";
            UserDomain groupDomain = new UserDomain();
            groupDomain.setCode(groupCode);
            List<UserDomain> domains = userDomainMapper.queryAllByLimit(groupDomain);
            if (!CollectionUtils.isEmpty(domains)) {
                UserDomain newGroupDomain = new UserDomain();
                // 将 层级组织(编辑/上传/下载)功能父模块id设为账号管理子模块id
                newGroupDomain.setParentModuleId(submoduleId);
                newGroupDomain.setId(domains.get(0).getId());
                userDomainMapper.update(newGroupDomain);
                // 将 账号管理子模块 name 修改为层级组织账号管理,code修改为LEVEL_ACCOUNT
                UserSubmodule newAccountSubmodule = new UserSubmodule();
                newAccountSubmodule.setId(submoduleId);
                newAccountSubmodule.setName("层级组织账号管理");
                newAccountSubmodule.setCode("LEVEL_ACCOUNT");
                userSubmoduleMapper.update(newAccountSubmodule);

                // 层级管理子模块id
                String levelSubmoduleId = domains.get(0).getParentModuleId();
                // 软删除层级管理子模块(LEVEL)
                UserSubmodule levelSubmodule = new UserSubmodule();
                levelSubmodule.setId(levelSubmoduleId);
                levelSubmodule.setDeleted(1);
                userSubmoduleMapper.update(levelSubmodule);

                // 清理套餐结构缓存
                redisUtil.del(STRUCT_KEY);
            }
        }
        return ServiceResult.success("success");
    }

    @Override
    public ServiceResult<String> rollbackMergePackage() {
        // 层级组织账号管理子模块code
        String levelAccountCode = "LEVEL_ACCOUNT";
        UserSubmodule accountSubmodule = new UserSubmodule();
        accountSubmodule.setCode(levelAccountCode);
        List<UserSubmodule> userSubmodules = userSubmoduleMapper.queryAllByLimit(accountSubmodule);
        if (!CollectionUtils.isEmpty(userSubmodules)) {
            // 子模块id
            String submoduleId = userSubmodules.get(0).getId();
            // code恢复为ACCOUNT, name恢复为 账号管理
            UserSubmodule newAccountSubmodule = new UserSubmodule();
            newAccountSubmodule.setId(submoduleId);
            newAccountSubmodule.setCode("ACCOUNT");
            newAccountSubmodule.setName("账号管理");
            userSubmoduleMapper.update(newAccountSubmodule);

            // 层级组织(编辑/上传/下载) 功能code
            String groupCode = "GROUP";
            UserDomain groupDomain = new UserDomain();
            groupDomain.setCode(groupCode);
            List<UserDomain> domains = userDomainMapper.queryAllByLimit(groupDomain);
            // 层级管理子模块code
            String levelCode = "LEVEL";
            UserSubmodule levelSubmodule = new UserSubmodule();
            levelSubmodule.setCode(levelCode);
            List<UserSubmodule> levelSubmodules = userSubmoduleMapper.queryAllByLimit(levelSubmodule);
            if (!CollectionUtils.isEmpty(domains) && !CollectionUtils.isEmpty(levelSubmodules)) {
                // 层级组织(编辑/上传/下载) 功能的父模块id指向LEVEL
                UserDomain newGroupDomain = new UserDomain();
                newGroupDomain.setId(domains.get(0).getId());
                newGroupDomain.setParentModuleId(levelSubmodules.get(0).getId());
                userDomainMapper.update(newGroupDomain);

                // 恢复软删除的层级管理子模块(LEVEL)
                UserSubmodule newLevelSubmodule = new UserSubmodule();
                newLevelSubmodule.setId(levelSubmodules.get(0).getId());
                newLevelSubmodule.setDeleted(0);
                userSubmoduleMapper.update(newLevelSubmodule);

                // 清理套餐结构缓存
                redisUtil.del(STRUCT_KEY);
            }

        }
        return ServiceResult.success("success");
    }

    /**
     * 初始化行业
     */
    @Override
    public void initIndustry() {
        OpenPlantFormBookingIndustryEnum[] values = OpenPlantFormBookingIndustryEnum.values();
        for (OpenPlantFormBookingIndustryEnum value : values) {
            OmIndustry existIndustry = omIndustryDao.findByCode(value.getIndex());
            if (existIndustry == null) {
                OmIndustry industry = new OmIndustry();
                industry.setId(new ObjectId().toHexString());
                industry.setCreateTime(LocalDateTime.now());
                industry.setUpdateTime(LocalDateTime.now());
                industry.setCode(value.getIndex());
                industry.setName(value.getName());
                omIndustryDao.insert(industry);
            } else {
                existIndustry.setUpdateTime(LocalDateTime.now());
                existIndustry.setCode(value.getIndex());
                existIndustry.setName(value.getName());
                omIndustryDao.updateNameByCode(value.getIndex(), value.getName());
            }
        }
    }

    /**
     * 初始化基础版套餐
     */
    public void initFreePackNew(String name) {
        String[] mModuleList = new String[]{
                "USER",
                "PROJECT",
                "MEMBER",
                "BI",
                "LIB"
        };
        String[] submoduleList = new String[]{
                "LEVEL_ACCOUNT",
                "CONFIG",
                "WALLET",
                "PROJECT_PROJECT",
                "PROJECT_EDIT",
                "NOTIFY",
                "DELIVER",
                "AWARD",
                "DATAREPORT",
                "MEMBER_INDIVIDUAL",
                "DASHBOARD",
                "TXTANLS"
        };
        String[] domainList = new String[]{
                "USER_QUOTA",
                "COMPANY_WALLET",
                "PROJECT_CREATE",
                "SURVEY_LOGIC",
                "PROJECT_OUTWARD",
                "DELIVER_LINK",
                "SMS_DELIVER",
                "EMAIL_DELIVER",
                "AWARD_AWARD",
                "DATA_VIEW",
                "SURVEY_QUOTA",
                "INDIVIDUAL_QUOTA",
                "EMBED_DELIVER"
        };
        // 更新基础版套餐
        UserPack userPack = new UserPack();
        userPack.setName(name);
        userPack.setOutName(name);
        userPack.setPrice(0);
        userPack.setUserQuota(1);
        userPack.setProjectQuota(5);
        userPack.setSurveyQuota(1000L);
        userPack.setMemberIndQuota(100);
        userPack.setBiDatasourceQuota(-1);
        userPack.setEdition(PackEditionEnum.PACK_EDITION_ENTERPRISE.getIndex());
        userPack.setType(PackageTypeEnum.FREE.getType());
        String packId = "";
        // 没有则新增，有则创建
        UserPack pack = omUserPackDao.getByName(name);
        if (pack == null) {
            userPack.setId(new ObjectId().toHexString());
            packId = userPack.getId();
            userPack.setCreateTime(LocalDateTime.now());
            userPack.setUpdateTime(LocalDateTime.now());
            omUserPackDao.insert(userPack);
        } else {
            packId = pack.getId();
            omUserPackDao.updateByPackName(userPack);
        }

        // 删除
        userModulePackDao.deleteByPackId(packId);
        // 模块
        for (String mCode : mModuleList) {
            UserMmodule userMmodule = userMmoduleMapper.findOneByCode(mCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userMmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.MODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 子模块
        for (String sCode : submoduleList) {
            UserSubmodule userSubmodule = userSubmoduleMapper.findOneByCode(sCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userSubmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.SUBMODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 功能
        for (String dCode : domainList) {
            UserDomain userDomain = userDomainMapper.findOneByCode(dCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userDomain.getId());
            userModulepack.setCategory(PackageCategoryEnum.DOMAIN.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
    }

    /**
     * 基础试用版套餐
     *
     * @param name
     */
    public void initTrialFreePack(String name) {
        String[] mModuleList = new String[]{
                "USER",
                "PROJECT",
                "ACTION",
                "MEMBER",
                "BI",
                "LIB"
        };
        String[] submoduleList = new String[]{
                "LEVEL_ACCOUNT",
                "CONFIG",
                "WALLET",
                "PROJECT_PROJECT",
                "PROJECT_EDIT",
                "NOTIFY",
                "DELIVER",
                "AWARD",
                "FISSION",
                "DATAREPORT",
                "MEMBER_INDIVIDUAL",
                "DASHBOARD",
                "TXTANLS"
        };
        String[] domainList = new String[]{
                "USER_QUOTA",
                "COMPANY_WALLET",
                "GROUP",
                "PROJECT_CREATE",
                "SURVEY_LOGIC",
                "PROJECT_OUTWARD",
                "WEB_LOGIC",
                "SURVEY_REPORT",
                "TICKET_RULE",
                "DELIVER_LINK",
                "SMS_DELIVER",
                "EMAIL_DELIVER",
                "EXPERT_LINK",
                "UPLOAD_ROSTER_DELIVER",
                "EMBED_DELIVER",
                "AWARD_AWARD",
                "MANAGE_FISSION",
                "DATA_VIEW",
                "DATAREPORT_SHARE",
                "SURVEY_QUOTA",
                "SURVEY_SAMPLE",
                "QUOTA",
                "INDIVIDUAL_QUOTA",
                "DASHBOARD_CREATE",
                "BI_SHARE",
                "TEXTANALYSE",
                "BI_DARK",
                "DATAREPORT_SHARE",
                "DASHBOARD_CREATE",
                "SURVEY_SAMPLE"
        };
        int userQuota = 1;
        int projectQuota = 5;
        long surveyQuota = 1000L;
        int memberQuota = 100;
        int datasource = -1;
        // 更新基础版套餐
        UserPack userPack = new UserPack();
        userPack.setName(name);
        userPack.setOutName(name);
        userPack.setPrice(0);
        userPack.setUserQuota(userQuota);
        userPack.setProjectQuota(projectQuota);
        userPack.setSurveyQuota(surveyQuota);
        userPack.setMemberIndQuota(memberQuota);
        userPack.setBiDatasourceQuota(datasource);
        userPack.setEdition(PackEditionEnum.PACK_EDITION_ENTERPRISE.getIndex());
        userPack.setType(PackageTypeEnum.FREE.getType());
        String packId = "";
        // 没有新增，则创建
        UserPack pack = omUserPackDao.getByName(name);
        if (pack == null) {
            userPack.setId(new ObjectId().toHexString());
            packId = userPack.getId();
            userPack.setCreateTime(LocalDateTime.now());
            userPack.setUpdateTime(LocalDateTime.now());
            omUserPackDao.insert(userPack);
        } else {
            packId = pack.getId();
            omUserPackDao.updateByPackName(userPack);
        }
        // 删除
        userModulePackDao.deleteByPackId(packId);
        // 模块
        for (String mCode : mModuleList) {
            UserMmodule userMmodule = userMmoduleMapper.findOneByCode(mCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userMmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.MODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 子模块
        for (String sCode : submoduleList) {
            UserSubmodule userSubmodule = userSubmoduleMapper.findOneByCode(sCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userSubmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.SUBMODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 功能
        for (String dCode : domainList) {
            UserDomain userDomain = userDomainMapper.findOneByCode(dCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userDomain.getId());
            userModulepack.setCategory(PackageCategoryEnum.DOMAIN.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
    }

    /**
     * 初始化高级版套餐
     *
     * @param name
     */
    public void initSeniorPack(String name) {
        String[] mModuleList = new String[]{
                "USER",
                "PROJECT",
                "ACTION",
                "MEMBER",
                "BI",
                "LIB"
        };
        String[] submoduleList = new String[]{
                "LEVEL_ACCOUNT",
                "CONFIG",
                "WALLET",
                "PROJECT_PROJECT",
                "PROJECT_EDIT",
                "NOTIFY",
                "DELIVER",
                "AWARD",
                "DATAREPORT",
                "MEMBER_INDIVIDUAL",
                "DASHBOARD",
                "TXTANLS"
        };
        String[] domainList = new String[]{
                "USER_QUOTA",
                "COMPANY_WALLET",
                "GROUP",
                "PROJECT_CREATE",
                "SURVEY_LOGIC",
                "PROJECT_OUTWARD",
                "WEB_LOGIC",
                "SURVEY_REPORT",
                "TICKET_RULE",
                "DELIVER_LINK",
                "SMS_DELIVER",
                "EMAIL_DELIVER",
                "EXPERT_LINK",
                "UPLOAD_ROSTER_DELIVER",
                "EMBED_DELIVER",
                "AWARD_AWARD",
                "DATA_VIEW",
                "DATAREPORT_SHARE",
                "SURVEY_QUOTA",
                "SURVEY_SAMPLE",
                "QUOTA",
                "INDIVIDUAL_QUOTA",
                "DASHBOARD_CREATE",
                "BI_SHARE",
                "TEXTANALYSE",
                "BI_DARK",
        };
        int userQuota = 5;
        int projectQuota = 10;
        long surveyQuota = 100000L;
        int memberQuota = -1;
        int datasource = -1;
        // 更新高级版套餐
        UserPack userPack = new UserPack();
        userPack.setName(name);
        userPack.setOutName(name);
        userPack.setPrice(0);
        userPack.setUserQuota(userQuota);
        userPack.setProjectQuota(projectQuota);
        userPack.setSurveyQuota(surveyQuota);
        userPack.setMemberIndQuota(memberQuota);
        userPack.setBiDatasourceQuota(datasource);
        userPack.setEdition(PackEditionEnum.PACK_EDITION_ENTERPRISE.getIndex());
        userPack.setType(PackageTypeEnum.SENIOR.getType());
        String packId = "";
        // 没有则新增，有则创建
        UserPack pack = omUserPackDao.getByName(name);
        if (pack == null) {
            userPack.setId(new ObjectId().toHexString());
            packId = userPack.getId();
            userPack.setCreateTime(LocalDateTime.now());
            userPack.setUpdateTime(LocalDateTime.now());
            omUserPackDao.insert(userPack);
        } else {
            packId = pack.getId();
            omUserPackDao.updateByPackName(userPack);
        }
        // 删除
        userModulePackDao.deleteByPackId(packId);
        // 模块
        for (String mCode : mModuleList) {
            UserMmodule userMmodule = userMmoduleMapper.findOneByCode(mCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userMmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.MODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 子模块
        for (String sCode : submoduleList) {
            UserSubmodule userSubmodule = userSubmoduleMapper.findOneByCode(sCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userSubmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.SUBMODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 功能
        for (String dCode : domainList) {
            UserDomain userDomain = userDomainMapper.findOneByCode(dCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userDomain.getId());
            userModulepack.setCategory(PackageCategoryEnum.DOMAIN.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
    }

    /**
     * 初始化专业版套餐
     *
     * @param name
     */
    public void initMajorPack(String name) {
        String[] mModuleList = new String[]{
                "USER",
                "PROJECT",
                "ACTION",
                "MEMBER",
                "BI",
                "LIB"
        };
        String[] submoduleList = new String[]{
                "LEVEL_ACCOUNT",
                "ROLE",
                "CONFIG",
                "SYSTEM",
                "WALLET",
                "PROJECT_PROJECT",
                "PROJECT_EDIT",
                "NOTIFY",
                "DELIVER",
                "AWARD",
                "FISSION",
                "DATAREPORT",
                "TICKET",
                "MEMBER_INDIVIDUAL",
                "MEMBER_INSTITUTION",
                "MEMBER_INTERIOR",
                "DASHBOARD",
                "TXTANLS",
                "DATASOURCE"
        };
        String[] domainList = new String[]{
                "USER_QUOTA",
                "ROLE_POWER",
                "DOCKING_WECHATWORK",
                "DOCKING_DINGTALK",
                "COMPANY_WALLET",
                "GROUP",
                "PROJECT_CREATE",
                "SURVEY_LOGIC",
                "PROJECT_OUTWARD",
                "WEB_LOGIC",
                "SURVEY_REPORT",
                "TICKET_RULE",
                "CREATE_NOTIFY",
                "OTHER_NOTIFY",
                "TWICE_DELIVER",
                "DELIVER_LINK",
                "SMS_DELIVER",
                "EMAIL_DELIVER",
                "EXPERT_LINK",
                "UPLOAD_ROSTER_DELIVER",
                "EMBED_DELIVER",
                "AWARD_AWARD",
                "AWARD_CARD",
                "MANAGE_FISSION",
                "DATA_VIEW",
                "DATAREPORT_SHARE",
                "SURVEY_QUOTA",
                "SURVEY_SAMPLE",
                "SURVEY_SPSS",
                "QUOTA",
                "TICKET_CREATE",
                "INDIVIDUAL_QUOTA",
                "MEMBER_PRECIPITATE",
                "MEMBER_LABEL",
                "INSTITUTION_MANAGE",
                "MEMBER_LABEL",
                "DASHBOARD_CREATE",
                "BI_SHARE",
                "TEXTANALYSE",
                "BI_DARK",
                "BI_CUSTOM",
                "ANTI_DISTUR",
                "DATASOURCE_QUOTA",
                "INTERIOR_MANAGE",
        };
        int userQuota = 20;
        int projectQuota = -1;
        long surveyQuota = 500000L;
        int memberIndQuota = -1;
        int memberGroupQuota = 20;
        int datasource = -1;
        // 更新基础版套餐
        UserPack userPack = new UserPack();
        userPack.setName(name);
        userPack.setOutName(name);
        userPack.setPrice(0);
        userPack.setUserQuota(userQuota);
        userPack.setProjectQuota(projectQuota);
        userPack.setSurveyQuota(surveyQuota);
        userPack.setMemberIndQuota(memberIndQuota);
        userPack.setMemberGroupQuota(memberGroupQuota);
        userPack.setBiDatasourceQuota(datasource);
        userPack.setEdition(PackEditionEnum.PACK_EDITION_ENTERPRISE.getIndex());
        userPack.setType(PackageTypeEnum.MAJOR.getType());
        String packId = "";
        // 没有则新增，有则创建
        UserPack pack = omUserPackDao.getByName(name);
        if (pack == null) {
            userPack.setId(new ObjectId().toHexString());
            packId = userPack.getId();
            userPack.setCreateTime(LocalDateTime.now());
            userPack.setUpdateTime(LocalDateTime.now());
            omUserPackDao.insert(userPack);
        } else {
            packId = pack.getId();
            omUserPackDao.updateByPackName(userPack);
        }
        // 删除
        userModulePackDao.deleteByPackId(packId);
        // 模块
        for (String mCode : mModuleList) {
            UserMmodule userMmodule = userMmoduleMapper.findOneByCode(mCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userMmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.MODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 子模块
        for (String sCode : submoduleList) {
            UserSubmodule userSubmodule = userSubmoduleMapper.findOneByCode(sCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userSubmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.SUBMODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 功能
        for (String dCode : domainList) {
            UserDomain userDomain = userDomainMapper.findOneByCode(dCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userDomain.getId());
            userModulepack.setCategory(PackageCategoryEnum.DOMAIN.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
    }

    /**
     * 初始化旗舰版套餐
     *
     * @param name
     */
    @Override
    public String initFlagShipPack(String name) {
        String[] mModuleList = new String[]{
                "USER",
                "PROJECT",
                "ACTION",
                "MEMBER",
                "BI",
                "LIB",
                "CUSTOMER_JOURNEY"
        };
        // 查询所有的submodule记录
        List<UserSubmodule> userSubmodules = userSubmoduleMapper.listSubModule();
        List<String> submoduleList = userSubmodules.stream().map(UserSubmodule::getCode).collect(Collectors.toList());
        // 查询所有的domain记录
        List<UserDomain> userDomains = userDomainMapper.listDomain();
        List<String> domainList = userDomains.stream().map(UserDomain::getCode).collect(Collectors.toList());

        int userQuota = -1;
        int projectQuota = -1;
        long surveyQuota = -1;
        int memberQuota = -1;
        //联系人分组限额
        int memberGroupQuota = 20;
        int datasource = -1;
        // 初始化旗舰版套餐
        UserPack userPack = new UserPack();
        userPack.setName(name);
        userPack.setOutName(name);
        userPack.setPrice(5000000);
        userPack.setUserQuota(userQuota);
        userPack.setProjectQuota(projectQuota);
        userPack.setSurveyQuota(surveyQuota);
        userPack.setMemberIndQuota(memberQuota);
        // 新增
        userPack.setMemberGroupQuota(memberGroupQuota);
        userPack.setBiDatasourceQuota(datasource);
        userPack.setEdition(PackEditionEnum.PACK_EDITION_ENTERPRISE.getIndex());
        userPack.setType(PackageTypeEnum.FLAGSHIP.getType());
        String packId;
        // 创建旗舰版套餐（没有则新增，有则创建）
        UserPack pack = omUserPackDao.getByName(name);
        if (pack == null) {
            userPack.setId(new ObjectId().toHexString());
            packId = userPack.getId();
            userPack.setCreateTime(LocalDateTime.now());
            userPack.setUpdateTime(LocalDateTime.now());
            omUserPackDao.insert(userPack);
        } else {
            packId = pack.getId();
            omUserPackDao.updateByPackName(userPack);
        }
        // 删除（套餐第一层）
        userModulePackDao.deleteByPackId(packId);
        // 创建第一层 模块
        for (String mCode : mModuleList) {
            UserMmodule userMmodule = userMmoduleMapper.findOneByCode(mCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userMmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.MODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 子模块
        for (String sCode : submoduleList) {
            UserSubmodule userSubmodule = userSubmoduleMapper.findOneByCode(sCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userSubmodule.getId());
            userModulepack.setCategory(PackageCategoryEnum.SUBMODULE.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        // 功能
        for (String dCode : domainList) {
            UserDomain userDomain = userDomainMapper.findOneByCode(dCode);
            UserModulepack userModulepack = new UserModulepack();
            userModulepack.setPackId(packId);
            userModulepack.setModuleId(userDomain.getId());
            userModulepack.setCategory(PackageCategoryEnum.DOMAIN.getIndex());
            userModulepack.setId(new ObjectId().toHexString());
            userModulepack.setCreateTime(LocalDateTime.now());
            userModulepack.setUpdateTime(LocalDateTime.now());
            userModulePackDao.insert(userModulepack);
        }
        return packId;
    }

    /**
     * 初始化套餐第一层功能
     */
    @Override
    public List<String> initModule() {
        List<UserMmodule> mmodules = new ArrayList<>();
        mmodules.add(new UserMmodule("USER", "企业管理", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 0));
        mmodules.add(new UserMmodule("CUSTOMER_JOURNEY", "客户旅程", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 1));
        mmodules.add(new UserMmodule("PROJECT", "问卷中心", MModuleCategoryEnum.MMODULE_CATEGORY_ADDED.getIndex(), 2));
        mmodules.add(new UserMmodule("ACTION", "行动记录", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 3));
        mmodules.add(new UserMmodule("MEMBER", "联系人", MModuleCategoryEnum.MMODULE_CATEGORY_ADDED.getIndex(), 4));
        mmodules.add(new UserMmodule("BI", "BI", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 5));
        mmodules.add(new UserMmodule("LIB", "模版库", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 6));
        mmodules.add(new UserMmodule("OPENPLATFORM", "开放平台", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 7));
        mmodules.add(new UserMmodule("ANALYSIS_WORKSHEET", "工作表", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 20));
        mmodules.add(new UserMmodule("ANALYSIS_DASHBOARD", "仪表盘", MModuleCategoryEnum.MMODULE_CATEGORY_BASE.getIndex(), 21));
        mmodules.add(new UserMmodule("ACTION_ALERT", "问卷预警", MModuleCategoryEnum.MMODULE_CATEGORY_ADDED.getIndex(), 22));
        mmodules.add(new UserMmodule("ACTION_TICKET", "工单", MModuleCategoryEnum.MMODULE_CATEGORY_ADDED.getIndex(), 23));
        mmodules.add(new UserMmodule("ANALYSIS_TXTANLS", "文本分析", MModuleCategoryEnum.MMODULE_CATEGORY_ADDED.getIndex(), 24));
        List<String> moduleIds = new ArrayList<>();
        for (UserMmodule mmodule : mmodules) {
            UserMmodule existModule = userMmoduleMapper.findOneByCode(mmodule.getCode());
            if (existModule == null) {
                mmodule.setId(new ObjectId().toHexString());
                mmodule.setCreateTime(LocalDateTime.now());
                mmodule.setUpdateTime(LocalDateTime.now());
                mmodule.setDeleted(0);
                moduleIds.add(mmodule.getId());
                userMmoduleMapper.insert(mmodule);
            } else {
                moduleIds.add(existModule.getId());
                existModule.setName(mmodule.getName());
                existModule.setCategory(mmodule.getCategory());
                existModule.setLevel(mmodule.getLevel());
                existModule.setUpdateTime(LocalDateTime.now());
                existModule.setDeleted(0);
                userMmoduleMapper.updateByCode(existModule);
            }
        }
        return moduleIds;
    }

    /**
     * 初始化套餐第二层功能
     */
    @Override
    public void initSubmodule() {
        // 企业管理
        HashMap<String, ArrayList<UserSubmodule>> submoduleMap = new HashMap<>(16);
        ArrayList<UserSubmodule> userSubmodules = new ArrayList<>();
        //20230330update
        //userSubmodules.add(new UserSubmodule("LEVEL_ACCOUNT", "层级组织账号管理"));
        userSubmodules.add(new UserSubmodule("ACCOUNT", "账号管理"));
        userSubmodules.add(new UserSubmodule("LEVEL", "层级管理"));
        userSubmodules.add(new UserSubmodule("WALLET", "企业钱包"));
        userSubmodules.add(new UserSubmodule("CONFIG", "配置管理"));
        userSubmodules.add(new UserSubmodule("SYSTEM", "系统对接"));
        userSubmodules.add(new UserSubmodule("CUSTOM", "定制开发"));
        userSubmodules.add(new UserSubmodule("ROLE", "角色与权限管理"));
        submoduleMap.put("USER", userSubmodules);
        // 客户旅程
        ArrayList<UserSubmodule> customerJourneySubmodules = new ArrayList<>();
        customerJourneySubmodules.add(new UserSubmodule("JOURNEY", "旅程管理"));
        submoduleMap.put("CUSTOMER_JOURNEY", customerJourneySubmodules);
        // 问卷中心
        ArrayList<UserSubmodule> projectSubmodules = new ArrayList<>();
        projectSubmodules.add(new UserSubmodule("PROJECT_PROJECT", "问卷项目数"));
        projectSubmodules.add(new UserSubmodule("PROJECT_EDIT", "问卷编辑"));
        projectSubmodules.add(new UserSubmodule("NOTIFY", "通知提醒"));
        projectSubmodules.add(new UserSubmodule("DELIVER", "投放问卷"));
        projectSubmodules.add(new UserSubmodule("AWARD", "管理奖励"));
        projectSubmodules.add(new UserSubmodule("FISSION", "裂变活动"));
        projectSubmodules.add(new UserSubmodule("DATAREPORT", "数据报表"));
        submoduleMap.put("PROJECT", projectSubmodules);
        // 行动记录
        ArrayList<UserSubmodule> actionSubmodules = new ArrayList<>();
        actionSubmodules.add(new UserSubmodule("TICKET", "手动创建工单"));
        submoduleMap.put("ACTION", actionSubmodules);
        // 联系人
        ArrayList<UserSubmodule> memberSubmodules = new ArrayList<>();
        memberSubmodules.add(new UserSubmodule("MEMBER_INDIVIDUAL", "个人联系人"));
        memberSubmodules.add(new UserSubmodule("MEMBER_INSTITUTION", "机构联系人"));
        memberSubmodules.add(new UserSubmodule("MEMBER_INTERIOR", "内部联系人"));
        submoduleMap.put("MEMBER", memberSubmodules);
        // BI
        ArrayList<UserSubmodule> biSubmodules = new ArrayList<>();
        biSubmodules.add(new UserSubmodule("DATASOURCE", "数据源"));
        biSubmodules.add(new UserSubmodule("DASHBOARD", "仪表盘"));
        biSubmodules.add(new UserSubmodule("TXTANLS", "文本分析"));
        submoduleMap.put("BI", biSubmodules);
        // 模版库
        ArrayList<UserSubmodule> libSubmodules = new ArrayList<>();
        libSubmodules.add(new UserSubmodule("COMPANY_LIB", "企业库"));
        libSubmodules.add(new UserSubmodule("OFFICIAL_LIB", "公共库"));
        submoduleMap.put("LIB", libSubmodules);
        // 开放平台
        ArrayList<UserSubmodule> openPlatformSubmodules = new ArrayList<>();
        openPlatformSubmodules.add(new UserSubmodule("OPENPLATFORM_API", "API"));
        submoduleMap.put("OPENPLATFORM", openPlatformSubmodules);

        List<UserMmodule> mmodules = userMmoduleMapper.listAllMmodule();
        Map<String, String> allMmoduleIdMap = mmodules.stream().collect(Collectors.toMap(UserMmodule::getCode, UserMmodule::getId));

        submoduleMap.forEach((key, value) -> {
            String parentCode = key;
            ArrayList<UserSubmodule> subList = value;
            String parentModuleId = allMmoduleIdMap.get(parentCode);
            // 遍历submodule
            for (int i = 0; i < subList.size(); i++) {
                UserSubmodule userSubmodule = subList.get(i);
                UserSubmodule existSubmodule = userSubmoduleMapper.findOneByCode(userSubmodule.getCode());
                if (existSubmodule == null) {
                    userSubmodule.setId(new ObjectId().toHexString());
                    userSubmodule.setParentModuleId(parentModuleId);
                    userSubmodule.setLevel(i);
                    userSubmodule.setCreatedDt(new Date());
                    userSubmodule.setUpdatedDt(new Date());
                    userSubmodule.setDeleted(0);
                    userSubmoduleMapper.insert(userSubmodule);
                } else {
                    existSubmodule.setName(userSubmodule.getName());
                    existSubmodule.setParentModuleId(parentModuleId);
                    existSubmodule.setLevel(i);
                    userSubmodule.setDeleted(0);
                    userSubmoduleMapper.updateByCode(existSubmodule);
                }
            }
        });
        // 删除废除的功能,暂无
    }

    /**
     * 初始化第三层功能
     */
    @Override
    public void initDomain() {
        HashMap<String, ArrayList<UserDomain>> domainMap = new HashMap<>(16);
        // ===========================企业管理==============================
        // 层级组织账号管理
//        ArrayList<UserDomain> accountDomains = new ArrayList<>();
//        accountDomains.add(new UserDomain("USER_QUOTA", "账号数(上传&手动添加)", true));
//        accountDomains.add(new UserDomain("GROUP", "层级组织(编辑/上传/下载)", false));
//        domainMap.put("LEVEL_ACCOUNT", accountDomains);
        ArrayList<UserDomain> accountDomains = new ArrayList<>();
        accountDomains.add(new UserDomain("USER_QUOTA", "账号数(上传&手动添加)", true));
        domainMap.put("ACCOUNT", accountDomains);

        ArrayList<UserDomain> groupDomains = new ArrayList<>();
        groupDomains.add(new UserDomain("GROUP", "层级组织(编辑/上传/下载)", false));
        domainMap.put("LEVEL", groupDomains);
        // 企业钱包
        ArrayList<UserDomain> walletDomains = new ArrayList<>();
        walletDomains.add(new UserDomain("COMPANY_WALLET", "企业钱包", false));
        domainMap.put("WALLET", walletDomains);
        // 配置管理
        ArrayList<UserDomain> configDomains = new ArrayList<>();
        configDomains.add(new UserDomain("COMPANY_LOGO", "个性化设置(logo登陆页等)", false));
        domainMap.put("CONFIG", configDomains);
        // 系统对接
        ArrayList<UserDomain> systemDomains = new ArrayList<>();
        systemDomains.add(new UserDomain("DOCKING_WECHATWORK", "对接企微", false));
        systemDomains.add(new UserDomain("DOCKING_DINGTALK", "对接钉钉", false));
        systemDomains.add(new UserDomain("DOCKING_WECHATMP", "授权微信公众号", false));
        domainMap.put("SYSTEM", systemDomains);
        // 定制开发
        ArrayList<UserDomain> customDomains = new ArrayList<>();
        customDomains.add(new UserDomain("CUSTOM_LINK_DELIVER", "自定义链接投放", false));
        domainMap.put("CUSTOM", customDomains);
        // 角色与权限管理
        ArrayList<UserDomain> roleDomains = new ArrayList<>();
        roleDomains.add(new UserDomain("ROLE_POWER", "角色与权限管理", false));
        domainMap.put("ROLE", roleDomains);
        // ===========================客户旅程==============================
        // 旅程管理
        ArrayList<UserDomain> journeyDomains = new ArrayList<>();
        journeyDomains.add(new UserDomain("JOURNEY_CREATE", "新建&编辑客户旅程", false));
        domainMap.put("JOURNEY", journeyDomains);
        // ===========================问卷中心==============================
        // 问卷项目数
        ArrayList<UserDomain> projectProjectDomains = new ArrayList<>();
        projectProjectDomains.add(new UserDomain("PROJECT_CREATE", "创建问卷项目", true));
        domainMap.put("PROJECT_PROJECT", projectProjectDomains);
        // 问卷编辑
        ArrayList<UserDomain> projectEditDomains = new ArrayList<>();
        projectEditDomains.add(new UserDomain("SURVEY_LOGIC", "答卷逻辑设置", false));
        projectEditDomains.add(new UserDomain("PROJECT_OUTWARD", "问卷外观自定义", false));
        projectEditDomains.add(new UserDomain("SPEECH_ANSWER", "语音答题", false));
        projectEditDomains.add(new UserDomain("WEB_LOGIC", "前端逻辑代码设置", false));
        projectEditDomains.add(new UserDomain("SURVEY_REPORT", "查看评分/答题报告", false));
        projectEditDomains.add(new UserDomain("SURVEY_LANGUAGE", "多语言调查问卷", false));
        domainMap.put("PROJECT_EDIT", projectEditDomains);
        // 通知提醒
        ArrayList<UserDomain> notifyDomains = new ArrayList<>();
        notifyDomains.add(new UserDomain("TICKET_RULE", "工单规则", false));
        notifyDomains.add(new UserDomain("CREATE_NOTIFY", "创建通知且跟进工单", false));
        notifyDomains.add(new UserDomain("OTHER_NOTIFY", "企业微信/飞书接收工单提醒", false));
        notifyDomains.add(new UserDomain("TWICE_DELIVER", "二次投放", false));
        domainMap.put("NOTIFY", notifyDomains);
        // 投放问卷
        ArrayList<UserDomain> deliverDomains = new ArrayList<>();
        deliverDomains.add(new UserDomain("DELIVER_LINK", "二维码/通用链接/组织链接", false));
        deliverDomains.add(new UserDomain("EXPERT_LINK", "专用链接", false));
        deliverDomains.add(new UserDomain("CUSTOM_DELIVER", "接口投放", false));
        deliverDomains.add(new UserDomain("UPLOAD_ROSTER_DELIVER", "上传名单投放", false));
        deliverDomains.add(new UserDomain("SMS_DELIVER", "短信投放", false));
        deliverDomains.add(new UserDomain("EMAIL_DELIVER", "邮件投放", false));
        deliverDomains.add(new UserDomain("EMBED_DELIVER", "网站/App嵌入投放", false));
        deliverDomains.add(new UserDomain("ANTI_DISTUR", "免打扰(单项目&跨项目)", false));
        deliverDomains.add(new UserDomain("WECHAT_DELIVER", "微信投放", false));
        deliverDomains.add(new UserDomain("WECHATMP_DELIVER", "微信投放-公众号投放", false));
        domainMap.put("DELIVER", deliverDomains);
        // 管理奖励
        ArrayList<UserDomain> awardDomains = new ArrayList<>();
        awardDomains.add(new UserDomain("AWARD_AWARD", "转盘抽奖", false));
        awardDomains.add(new UserDomain("AWARD_REDPACKET_AWARD", "微信红包", false));
        awardDomains.add(new UserDomain("AWARD_CARD", "微信支付宝卡劵、第三方奖励链接", false));
        awardDomains.add(new UserDomain("AWARD_CUSTOM", "定制奖励", false));
        awardDomains.add(new UserDomain("AWARD_LOGO", "领奖页logo配置", false));
        awardDomains.add(new UserDomain("AWARD_BRAND_POINTS", "品牌积分", false));
        domainMap.put("AWARD", awardDomains);
        // 裂变活动
        ArrayList<UserDomain> fissionDomains = new ArrayList<>();
        fissionDomains.add(new UserDomain("MANAGE_FISSION", "管理裂变", false));
        domainMap.put("FISSION", fissionDomains);
        // 数据报表
        ArrayList<UserDomain> dataReportDomains = new ArrayList<>();
        dataReportDomains.add(new UserDomain("DATA_VIEW", "查看数据看板", false));
        dataReportDomains.add(new UserDomain("SURVEY_QUOTA", "答卷限额", true));
        dataReportDomains.add(new UserDomain("SURVEY_SAMPLE", "不合格样本自动剔除", false));
        dataReportDomains.add(new UserDomain("SURVEY_SPSS", "SPSS等多种样式导出", false));
        dataReportDomains.add(new UserDomain("QUOTA", "配额管理", false));
        dataReportDomains.add(new UserDomain("DATAREPORT_SHARE", "分享数据看板", false));
        dataReportDomains.add(new UserDomain("BATCH_EXPORT", "批量导出答题附件", false));
        domainMap.put("DATAREPORT", dataReportDomains);
        // ===========================行动记录==============================
        // 手动创建工单
        ArrayList<UserDomain> ticketDomains = new ArrayList<>();
        ticketDomains.add(new UserDomain("TICKET_CREATE", "手动创建工单", false));
        domainMap.put("TICKET", ticketDomains);
        // ===========================联系人==============================
        // 个人联系人
        ArrayList<UserDomain> memberIndividualDomains = new ArrayList<>();
        memberIndividualDomains.add(new UserDomain("INDIVIDUAL_QUOTA", "个人联系人限额", true));
        memberIndividualDomains.add(new UserDomain("MEMBER_GROUP_QUOTA", "联系人分组", true));
        memberIndividualDomains.add(new UserDomain("MEMBER_PRECIPITATE", "自动沉淀联系人", false));
        memberIndividualDomains.add(new UserDomain("MEMBER_LABEL", "标签管理功能", false));
        domainMap.put("MEMBER_INDIVIDUAL", memberIndividualDomains);
        // 机构联系人
        ArrayList<UserDomain> memberInstitutionDomains = new ArrayList<>();
        memberInstitutionDomains.add(new UserDomain("INSTITUTION_MANAGE", "机构联系人管理功能", false));
        memberInstitutionDomains.add(new UserDomain("INTERIOR_MANAGE", "内部联系人管理功能", false));
        domainMap.put("MEMBER_INSTITUTION", memberInstitutionDomains);
        // 内部联系人
        ArrayList<UserDomain> memberInteriorDomains = new ArrayList<>();
        memberInteriorDomains.add(new UserDomain("INTERIOR_MANAGE", "内部联系人管理功能", false));
        domainMap.put("MEMBER_INTERIOR", memberInteriorDomains);
        // ===========================BI==============================
        // 数据源
        ArrayList<UserDomain> dataSourceDomains = new ArrayList<>();
        dataSourceDomains.add(new UserDomain("DATASOURCE_QUOTA", "创建数据源", false));
        dataSourceDomains.add(new UserDomain("DATASOURCE_TRANSLATE", "编辑语言", false));
        domainMap.put("DATASOURCE", dataSourceDomains);
        // ===========================BI==============================
        // 仪表盘
        ArrayList<UserDomain> dashboardDomains = new ArrayList<>();
        dashboardDomains.add(new UserDomain("DASHBOARD_CREATE", "创建仪表盘", false));
        dashboardDomains.add(new UserDomain("BI_SHARE", "分享协作", false));
        dashboardDomains.add(new UserDomain("TEXTANALYSE", "词频分析", false));
        dashboardDomains.add(new UserDomain("BI_DARK", "深色模式", false));
        dashboardDomains.add(new UserDomain("BI_CUSTOM", "前端定制图表", false));
        dashboardDomains.add(new UserDomain("DASHBOARD_TRANSLATE", "编辑语言", false));
        dashboardDomains.add(new UserDomain("DASHBOARD_SHARE", "仪表盘分享", false));
        domainMap.put("DASHBOARD", dashboardDomains);
        // 文本分析
        ArrayList<UserDomain> txtanlsDomains = new ArrayList<>();
        txtanlsDomains.add(new UserDomain("TXTANLS_CREATE", "新增文本分析", false));
        txtanlsDomains.add(new UserDomain("MANAGE_PROJECT", "管理项目", false));
        domainMap.put("TXTANLS", txtanlsDomains);
        // ===========================模版库==============================
        // 企业库
        ArrayList<UserDomain> companyLibDomains = new ArrayList<>();
        companyLibDomains.add(new UserDomain("COMPANY_LIBRARY", "企业库", false));
        domainMap.put("COMPANY_LIB", companyLibDomains);
        ArrayList<UserDomain> officialLibDomains = new ArrayList<>();
        // 公共库
        officialLibDomains.add(new UserDomain("OFFICIAL_LIBRARY", "公共库", false));
        domainMap.put("OFFICIAL_LIB", officialLibDomains);
        // ===========================开放平台==============================
        // API
        ArrayList<UserDomain> openPlatformDomains = new ArrayList<>();
        openPlatformDomains.add(new UserDomain("AES_API", "Asccess_token_API", false));
        domainMap.put("OPENPLATFORM_API", openPlatformDomains);

        // 查询所有的submodule记录
        List<UserSubmodule> userSubmodules = userSubmoduleMapper.listSubModule();
        Map<String, String> allSubModuleMap = userSubmodules.stream().collect(Collectors.toMap(UserSubmodule::getCode, UserSubmodule::getId));

        domainMap.forEach((key, value) -> {
            String parentCode = key;
            ArrayList<UserDomain> domainArrayList = value;
            String parentModuleId = allSubModuleMap.get(parentCode);
            // 遍历domainList
            for (int i = 0; i < domainArrayList.size(); i++) {
                UserDomain userDomain = domainArrayList.get(i);
                UserDomain existDomain = userDomainMapper.findOneByCode(userDomain.getCode());
                // 不存在则新增，否则更新
                if (existDomain == null) {
                    userDomain.setId(new ObjectId().toHexString());
                    userDomain.setParentModuleId(parentModuleId);
                    userDomain.setLevel(i);
                    userDomain.setCreateTime(LocalDateTime.now());
                    userDomain.setUpdateTime(LocalDateTime.now());
                    userDomain.setDeleted(0);
                    userDomainMapper.insert(userDomain);
                } else {
                    existDomain.setParentModuleId(parentModuleId);
                    existDomain.setLevel(i);
                    existDomain.setUpdateTime(LocalDateTime.now());
                    existDomain.setCode(userDomain.getCode());
                    existDomain.setName(userDomain.getName());
                    existDomain.setIsQuota(userDomain.getIsQuota());
                    existDomain.setDeleted(0);
                    userDomainMapper.updateByCode(existDomain);
                }
            }
        });
        // 删除废除的功能,暂无
        redisUtil.del(STRUCT_KEY);
    }

    /**
     * 私有部署的在更新配置后需要删除套餐缓存
     */
    @Override
    public void deletePackageCache() {
        if (singleOrgCode != null) {
            Organization org = omOrgGrpcService.getByIdOrCode(null, singleOrgCode);
            if (org != null) {
                redisUtil.del(String.format(USER_PACK_PERM, org.getId()));
            }
        }
    }


}
